package org.qf.web;

import org.qf.pojo.SmbmsUser;
import org.qf.service.SmbmsUserService;
import org.qf.service.impl.SmbmsUserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet(value = "/addUserServlet")
public class AddUserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        SmbmsUser smbmsUser = new SmbmsUser();
        //从界面获取数据
        // 用户编号
        String userCode = req.getParameter("userId");
        // 用户名称
        String userName = req.getParameter("userName");
        // 用户密码
        String pwd = req.getParameter("userpassword");
        // 性别
        String sex = req.getParameter("gender");
        int gender = Integer.parseInt(sex);
        // 出生日期
        String data = req.getParameter("data");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date birthday = format.parse(data);
            // 电话
            String phone = req.getParameter("userphone");
            // 地址
            String address = req.getParameter("userAddress");
            // 角色
            String userLei = req.getParameter("role");
            int userRole = Integer.parseInt(userLei);
            smbmsUser.setUserCode(userCode);
            smbmsUser.setUserName(userName);
            smbmsUser.setGender(gender);
            smbmsUser.setUserPassword(pwd);
            smbmsUser.setBirthday(birthday);
            smbmsUser.setPhone(phone);
            smbmsUser.setAddress(address);
            smbmsUser.setUserRole(userRole);
            // 创建人, 当前登录人 怎么获取session
            HttpSession session = req.getSession();
            SmbmsUser userSession = (SmbmsUser)
                    session.getAttribute("userSession");
            smbmsUser.setCreatedBy(userSession.getId());
            // 当前时间
            smbmsUser.setCreationDate(new Date());
            // 调用业务层接口
            SmbmsUserService smbmsUserService = new SmbmsUserServiceImpl();
            int i = smbmsUserService.addUser(smbmsUser);
            if (i > 0) {
                //添加成功
                req.getRequestDispatcher("/userServlet").forward(req, resp);
            } else {
                // 添加失败
                resp.sendRedirect("userAdd.jsp");
            }
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
